package org.demo.system.service.impl;

import org.demo.base.auth.domain.Permission;
import org.demo.base.auth.domain.Role;
import org.demo.system.mapper.RoleMapper;
import org.demo.system.service.PermissionService;
import org.demo.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author tomdog
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionService permissionService;

    /**
     * 根据用户id查询所有角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> listByUserId(Long userId) {
        List<Role> roles = roleMapper.listByUserId(userId);
        // 关联查询所有权限
        Set<String> roleKeys = roles.stream().map(Role::getRoleKey).collect(Collectors.toSet());
        if(!CollectionUtils.isEmpty(roleKeys)) {
            List<Permission> permissions = permissionService.listByRoleKeys(roleKeys);
            // 把权限赋值到角色中
            if(!CollectionUtils.isEmpty(permissions)) {
                // 按照角色key分组
                Map<String, List<Permission>> permissionsMap =
                        permissions.stream().collect(Collectors.groupingBy(Permission::getRoleKey));
                // 分别设置到角色对象中
                roles.forEach(r -> {
                    List<Permission> permissions1 = permissionsMap.get(r.getRoleKey());
                    r.setPermissions(permissions1);
                });
            }
        }
        return roles;
    }

    @Override
    public void addRoleForUser(Long userId, String... roleKey) {
       roleMapper.addRoleForUser(userId, roleKey);
    }
}
